/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-05-10 09:04:02
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-11-04 18:30:44
 */
import React from "react";
import utils from "@/common/utils";
import "./index.scss";

export type Props = {
  data?: { text: string; value: string; check?: boolean }[];
  title?: string;
  style?: object;
  type?: "radio" | "checkbox";
  visible: boolean;
  onCancel?: Function;
  onChange?: Function;
  footer?: any[];
};
type State = {
  data?: { text: string; value: string; check?: boolean }[];
  visible: boolean;
};

export default class CustomRange extends React.Component<Props, State> {
  constructor(props: Props | Readonly<Props>) {
    super(props);
    this.state = {
      visible: props.visible,
      data: props.data
    };
  }

  componentWillReceiveProps(props) {
    if (props.visible != this.props.visible) {
      this.setState({
        visible: props.visible
      });
    }

  }

  render() {
    const {
      title,
      style,
      type = "radio",
      onCancel,
      onChange,
      footer
    } = this.props;
    const { data, visible } = this.state;
    return (
      <div
        className="cx-picker"
        style={{ display: visible ? "block" : "none", ...style }}
      >
        <div className="picker-content">
          <div className="picker-content-header">
            <div className="picker-content-header-title">{title}</div>
            <div
              onClick={() => {
                onCancel && onCancel();
              }}
              className="icon-close"
            />
          </div>

          {this.state.data?.map((item, index) => (
            <div
              key={index}
              className="picker-content-item"
              onClick={() => {
                const deep = utils.obj.deepClone(data);
                if (type === "radio") {
                  deep.map((item) => (item.check = false));
                  deep[index].check = true;
                } else {
                  deep[index].check = !item.check;
                }

                this.setState(
                  {
                    data: deep
                  },
                  () => {
                    onChange &&
                      onChange(this.state.data[index], this.state.data);
                  }
                );
              }}
            >
              <p className={`text ${item.check && "active-text"}`}>
                {item.text}
              </p>
              {item.check === true ? (
                <p className="icon-check check" />
              ) : (
                <div className="select" />
              )}
            </div>
          ))}

          {footer && <div style={{ display: "flex" }}>{...footer}</div>}
        </div>
      </div>
    );
  }
}
